package com.atguigu.day02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/3/30
 * 该案例演示了并行度
 * 概念：一个算子子任务的个数称之为并行度
 * 一个应用程序的并行度取决于并行度最大的算子的子任务的个数
 * 在开发环境中，如果没有指定并行度，默认并行度的个数是 cpu的线程数
 * 可以通过如下几种方式指定并行度
 *      代码中全局指定并行度
 *          env.setParallelism(2);
 *      单独为算子执行并行度
 *          .setParallelism(2);
 *      在flink-conf.xml配置文件中指定
 *          parallelism.default: 1
 *      在命令行提交应用的时候指定并行度
 *          -p 个数
 *      优先级：
 *          单独为算子执行并行度 > 代码中全局指定并行度 > 在命令行提交应用的时候指定并行度 > 在flink-conf.xml配置文件中指定
 *
 */
public class Flink01_par {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //Configuration conf = new Configuration();
        //conf.set(RestOptions.PORT,8088);
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        //全局指定并行度
        env.setParallelism(2);

        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.扁平化
        SingleOutputStreamOperator<String> flatMapDS = socketDS.flatMap(
                new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String lineStr, Collector<String> out) throws Exception {
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            out.collect(word);
                        }
                    }
                }
        );
        //TODO 4.对类型进行转换    String->Tuple2<String,Long>
        SingleOutputStreamOperator<Tuple2<String, Long>> tupDS = flatMapDS.map(
                new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String word) throws Exception {
                        return Tuple2.of(word, 1L);
                    }
                }
        ).setParallelism(3);
        //TODO 5.按照单词进行分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = tupDS.keyBy(0);
        //TODO 6.计数
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyedDS.sum(1);
        //TODO 7.输出结果
        sumDS.print();
        //TODO 8.提交作业
        env.execute();
    }
}
